package leetcode_301_400;

import java.util.*;

public class LeeCode_350 {
    public static void main(String[] args) {
//        System.out.println(Arrays.toString(intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
        System.out.println(Arrays.toString(intersect(new int[]{4, 9, 5}, new int[]{9, 4, 9, 8, 4})));
    }
    private static int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>();
        Map<Integer, Integer> map1 = new HashMap<>();
        for (int num : nums1) {
            if (map1.containsKey(num)){
                map1.put(num, map1.get(num) + 1);
                continue;
            }
            map1.put(num, 1);
        }
        Arrays.sort(nums2);
        int index = 0;
        while (index < nums2.length){
            int num = nums2[index];
            if (map1.containsKey(num)){
                int count1 = map1.get(num);
                int count2 = 0;
                while (index < nums2.length && nums2[index] == num){
                    index++;
                    count2++;
                }
                for (int i = 0; i < Math.min(count1, count2); i++) {
                    list.add(num);
                }
            }else {
                index++;
            }
        }
        int[] ans = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ans[i] = list.get(i);
        }
        return ans;
    }
}
